package Util

import (
	"encoding/json"
	"reflect"
)

func StructToMapUseTag(data interface{}, tag string) (result map[string]interface{}) {
	switch tag {
	case "json":
		//结构体转json
		if jsonData, err := json.Marshal(&data); err != nil {
			return
		} else {
			//json转map
			err = json.Unmarshal(jsonData, &result)
		}
	default:
		obj1 := reflect.TypeOf(data)
		obj2 := reflect.ValueOf(data)
		result = make(map[string]interface{})
		for i := 0; i < obj1.NumField(); i++ {
			if obj2.Field(i).CanInterface() {
				result[obj1.Field(i).Tag.Get(tag)] = obj2.Field(i).Interface()
			}
		}
	}

	return
}
